#include "camview.h"

CamView::CamView()
{
	detector = NULL;
}

void CamView::setDetector(Detector* detector)
{
    this->detector = detector;
}

void CamView::newFrame(const cv::Mat& frame)
{
	mutex.lock();
    this->frame = frame.clone();
	mutex.unlock();
    update();
}

void CamView::paintEvent(QPaintEvent *event)
{
    if(frame.empty()) {
        return;
    }

    mutex.lock();
    QImage image = Mat2QImage(frame);
    mutex.unlock();

    QPainter painter(this);
    painter.drawImage(QPoint(0, 0), image);

    painter.setFont(QFont("Monospace", 14));
    QString str = QString::number(image.width()) +\
            "x" + QString::number(image.height());
    painter.drawText(10, 25, str);

    if(detector) {
        std::vector<cv::Rect> objects;
        detector->detect(frame, objects);

        painter.setPen(QPen(Qt::red, 2));

        for(std::vector<cv::Rect>::iterator\
            it=objects.begin(); it!=objects.end(); ++it) {
            painter.drawRect(it->x, it->y,\
                             it->width, it->height);
        }
    }
}

QImage CamView::Mat2QImage(const cv::Mat& frame)
{
    IplImage cvimage = (IplImage)frame;
    return QImage((const uchar *)cvimage.imageData, cvimage.width, cvimage.height, QImage::Format_RGB888).rgbSwapped();
}

CamView::~CamView()
{

}
